const { http } = require('../../../utils/http.js')
const { noteService } = require('../../../utils/noteService.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 当前题目索引(从0开始)和总题目数
    currentIndex: 0,
    totalQuestions: 0,
    
    // 答题模式
    mode: 'answer', // answer 或 recite
    
    // 题目数据
    questionData: {},
    
    // 显示控制
    showOptions: true,  // 修改为true，让选项默认显示
    showResult: false,
    showAnalysis: false,
    showAnswerCardModal: false,
    showSubmitConfirm: false, // 交卷确认弹窗
    
    // 答题结果
    userAnswer: '',
    correctAnswer: '',
    totalAnswers: 0,
    correctRate: 0,
    
    // 当前标签页
    activeTab: 'analysis',
    
    // 笔记
    noteText: '',
    isFavorite: false,
    
    // 答题卡数据 - 状态: unanswered, correct, wrong
    questionNumbers: [],

    // 路由参数
    questionBankId: null,
    subjectId: null,
    // 从后端加载的题目集合
    questions: [],
    // 题目ID -> 选项 映射（缓存已加载的数据）
    questionOptionsMap: {},
    // 答题状态记录，键为题目索引，值为状态
    answerStatus: {},
    
    // 新增：题目ID映射，键为题目索引，值为题目ID
    questionIdMap: {},        // 例如：{0: '123', 1: '456', 2: '789'}
    
    // 新增：答题状态增强，包含题目ID和答题信息
    enhancedAnswerStatus: {}, // 例如：{0: {status: 'correct', questionId: '123', userAnswer: 'A', timestamp: 1234567890}}
    
    // 答题统计（计算属性）
    answeredCount: 0,
    correctCount: 0,
    wrongCount: 0,
    unansweredCount: 0,
    progressPercentage: 0,
    
    // 新增：控制是否显示详细内容（解析、点评、笔记）
    showDetailContent: false, // 默认不显示，只在查看错题解析或记录时显示
    detailContentMode: 'normal', // 详细内容模式：normal(正常答题), review(错题复习), record(查看记录)
    
    // 计时相关
    startTime: null,        // 答题开始时间
    elapsedSeconds: 0,      // 已过秒数
    timerInterval: null,    // 计时器ID
    isTimerRunning: false,  // 计时器是否运行中
    
    // 错题相关
    isAddedToWrongQuestions: false,  // 当前题目是否已添加到错题库
    isFavorite: false, // 标记当前题目是否收藏（del=1为true，del=0或无记录为false ）
  },

  /**
   * 根据题库ID获取题目列表（仅加载题目基本信息，不批量拉取选项/评论）
   */
  fetchQuestionsByBankId(bankId) {
    wx.showLoading({ title: '加载题目...' })
    http.get(`/fk/question_bank/questions/${bankId}`)
      .then(res => {
        wx.hideLoading()
        const list = (res && res.data) ? res.data : res

        
        // 初始化题目状态数组（未答）
        const questionNumbers = list.map((_, idx) => ({ 
          number: idx + 1, 
          status: 'unanswered' 
        }))
        
        // 初始化题目ID映射
        const questionIdMap = {};
        list.forEach((question, index) => {
          const questionId = question.id || question.question_id || question.questionId || `q_${index}`;
          questionIdMap[index] = questionId;
        });
        
        this.setData({
          questions: list,
          totalQuestions: list.length,
          currentIndex: 0,
          questionNumbers,
          questionIdMap,        // 新增：题目ID映射
          answerStatus: {},     // 重置答题状态
          enhancedAnswerStatus: {} // 重置增强答题状态
        })

        // 存储题目数据到本地存储，供其他页面使用
        try {
          const storageKey = `questions_${bankId}`;
          wx.setStorageSync(storageKey, list);
  
        } catch (e) {
          console.error('存储题目数据失败:', e);
        }

        // 更新答题统计
        this.updateAnswerStats();

        // 加载第一题数据（触发第一题的选项/评论请求）
        if (list.length > 0) {
          this.loadQuestionData(0)
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('获取题目失败:', err)
        wx.showToast({ title: '获取题目失败', icon: 'none' })
      })
  },

  /**
   * 将后端题目结构映射为页面需要的结构
   */
  transformBackendQuestion(item) {
    
    
    const title = item.title || item.name || item.questionTitle || '章节练习';
    const content = item.content || item.stem || item.question || item.questionContent || '';
    const type = item.type || item.questionType || '单选';
    const difficulty = Number(item.difficulty || item.questionDifficulty || 3);
    const analysis = item.analysis || item.explain || item.questionAnalysis || '';

    // 处理选项（基础映射，详细选项从接口拉取）
    let optionsRaw = item.options || item.choices || [];
    if (typeof optionsRaw === 'string') {
      optionsRaw = optionsRaw.split(/\n|;|\|/).filter(Boolean);
    }
    const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
    let correctKey = item.correctAnswer || item.answer || item.correctOptions || '';
    if (typeof correctKey === 'number') {
      correctKey = labels[correctKey] || '';
    }
    
    // 创建基础选项结构
    const options = (optionsRaw || []).slice(0, labels.length).map((opt, i) => ({
      label: labels[i],
      text: typeof opt === 'string' ? opt : (opt.text || opt.content || ''),
      isCorrect: false, // 临时默认，后续用接口数据覆盖
      isSelected: false
    }));

    // 如果没有选项，创建默认的空选项
    if (options.length === 0) {
      for (let i = 0; i < 4; i++) {
        options.push({
          label: labels[i],
          text: '',
          isCorrect: false,
          isSelected: false
        });
      }
    }

    return {
      title,
      type,
      content,
      difficulty,
      analysis,
      options,
      correctAnswer: String(correctKey).toUpperCase() || 'A'
    };
  },

  /**
   * 按题目ID获取选项（仅在切换到该题时调用）
   */
  fetchOptionsByQuestionId(questionId, questionIndex) {
    // 避免重复请求
    if (this.data.questionOptionsMap[questionId]) return;
    
    http.get(`/ssh/questionOption/queryByQuestionId/${questionId}`)
      .then(res => {
        // 检查响应状态
        if (res && res.code === 500) {
          console.error('获取选项失败 - 后端错误:', res);
          
          // 检查是否是 TooManyResultsException
          const errorMsg = res.data?.msg || '';
          if (errorMsg.includes('TooManyResultsException') || errorMsg.includes('found: 2')) {
            // 这是数据库重复数据问题
            wx.showModal({
              title: '数据异常',
              content: '该题目存在重复的选项数据，请联系管理员清理数据库。是否跳过此题？',
              confirmText: '跳过此题',
              cancelText: '重试',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  // 跳过此题，显示基础信息
                  this.showBasicQuestionInfo(questionIndex);
                  // 标记此题已处理，避免重复请求
                  const map = { ...this.data.questionOptionsMap, [questionId]: 'error' };
                  this.setData({ questionOptionsMap: map });
                } else {
                  // 重试加载选项
                  setTimeout(() => {
                    this.retryLoadOptions(questionId, questionIndex);
                  }, 1000);
                }
              }
            });
          } else {
            // 其他500错误
            wx.showModal({
              title: '选项加载失败',
              content: '该题目的选项数据有问题，请联系管理员修复。是否重试？',
              confirmText: '重试',
              cancelText: '跳过',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  // 重试加载选项
                  setTimeout(() => {
                    this.retryLoadOptions(questionId, questionIndex);
                  }, 1000);
                } else {
                  // 跳过此题，显示基础信息
                  this.showBasicQuestionInfo(questionIndex);
                }
              }
            });
          }
          return;
        }
        
        const options = (res && res.data) ? res.data : res;

        
        // 检查选项数据是否有效
        if (!options || (typeof options === 'object' && Object.keys(options).length === 0)) {
          console.warn('选项数据为空:', options);
          // 移除提示，静默处理
          // wx.showToast({ 
          //   title: '该题目暂无选项', 
          //   icon: 'none',
          //   duration: 2000
          // });
          return;
        }
        
        const map = { ...this.data.questionOptionsMap, [questionId]: options };
        this.setData({ questionOptionsMap: map });

        // 如果是当前题，立即更新选项
        if (questionIndex === this.data.currentIndex) {
          const { questions } = this.data;
          const cur = questions[questionIndex];
          const mapped = this.transformBackendQuestion(cur);
          const built = this.buildOptionsFromBackendOptions(options, mapped.correctAnswer);
          mapped.options = built.options;
          mapped.correctAnswer = built.correctLabel || mapped.correctAnswer;
          
          this.setData({
            questionData: mapped,
            correctAnswer: mapped.correctAnswer
          });
        }
      })
      .catch(err => {
        console.error('获取选项失败', questionId, err);
        
        // 静默处理错误，自动重试
        console.warn('选项加载失败，自动重试:', err);
        
        // 延迟重试，避免频繁请求
        setTimeout(() => {
          this.retryLoadOptions(questionId, questionIndex);
        }, 1000);
        
        // 移除弹窗提示，改为静默处理
        // 根据错误类型提供不同的提示
        // let errorMessage = '选项加载失败';
        // if (err && err.code === 500) {
        //   errorMessage = '选项加载失败，请联系管理员';
        // } else if (err && err.message) {
        //   errorMessage = err.message;
        // }
        
        // wx.showModal({
        //   title: '选项加载失败',
        //   content: '网络请求失败，是否重试？',
        //   confirmText: '重试',
        //   cancelText: '跳过',
        //   success: (modalRes) => {
        //     if (modalRes.confirm) {
        //       // 重试加载选项
        //       setTimeout(() => {
        //         this.retryLoadOptions(questionId, questionIndex);
        //       }, 1000);
        //     } else {
        //       // 跳过此题，显示基础信息
        //       this.showBasicQuestionInfo(questionIndex);
        //     }
        //   }
        // });
      });
  },

  /**
   * 重试加载选项
   */
  retryLoadOptions(questionId, questionIndex) {
    
    // 检查重试次数
    const retryKey = `retry_${questionId}`;
    const retryCount = this.data[retryKey] || 0;
    
    if (retryCount >= 3) {
      console.warn('选项重试次数已达上限:', questionId);
      // 移除提示，静默处理
      // wx.showToast({
      //   title: '重试次数已达上限，跳过此题',
      //   icon: 'none',
      //   duration: 2000
      // });
      
      // 跳过此题，显示基础信息
      this.showBasicQuestionInfo(questionIndex);
      // 标记此题已处理，避免重复请求
      const map = { ...this.data.questionOptionsMap, [questionId]: 'error' };
      this.setData({ questionOptionsMap: map });
      return;
    }
    
    // 增加重试次数
    this.setData({ [retryKey]: retryCount + 1 });
    
    // 清除缓存，重新请求
    const map = { ...this.data.questionOptionsMap };
    delete map[questionId];
    this.setData({ questionOptionsMap: map });
    
    // 移除重试提示，静默重试
    // wx.showToast({
    //   title: `第${retryCount + 1}次重试...`,
    //   icon: 'none',
    //   duration: 1000
    // });
    
    // 延迟重试，避免频繁请求
    setTimeout(() => {
      this.fetchOptionsByQuestionId(questionId, questionIndex);
    }, 1000);
  },

  /**
   * 显示基础题目信息（无选项）
   */
  showBasicQuestionInfo(questionIndex) {
    const { questions } = this.data;
    if (!questions[questionIndex]) return;
    
    const mapped = this.transformBackendQuestion(questions[questionIndex]);
    
    // 创建默认选项
    const defaultOptions = [
      { label: 'A', text: '选项A', isCorrect: false, isSelected: false },
      { label: 'B', text: '选项B', isCorrect: false, isSelected: false },
      { label: 'C', text: '选项C', isCorrect: false, isSelected: false },
      { label: 'D', text: '选项D', isCorrect: false, isSelected: false }
    ];
    
    mapped.options = defaultOptions;
    
    // 更新题目数据
    this.setData({
      questionData: mapped,
      correctAnswer: mapped.correctAnswer
    });
    
    // 在答题卡中标记此题有问题
    const questionNumbers = [...this.data.questionNumbers];
    if (questionNumbers[questionIndex]) {
      questionNumbers[questionIndex].status = 'error';
      questionNumbers[questionIndex].hasError = true;
      this.setData({ questionNumbers });
    }
    
    // 移除提示，静默显示基础信息
    // wx.showToast({
    //   title: '显示基础题目信息',
    //   icon: 'none',
    //   duration: 2000
    // });
  },



  /**
   * 切换模式（答题/背题）
   */
  switchMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ mode }, () => {
      // 背题模式默认显示选项和答案
      if (mode === 'recite') {
        this.setData({ showOptions: true, showResult: true, showAnalysis: true })
      }
    });
  },

  /**
   * 选择选项并判断对错
   */
  selectOption(e) {
    const index = e.currentTarget.dataset.index;
    const options = [...this.data.questionData.options]; // 拷贝数组避免直接修改原数据
    const currentIndex = this.data.currentIndex;
    
    // 如果已经答过这道题，不允许重复作答
    if (this.data.answerStatus[currentIndex]) {
      wx.showToast({
        title: '此题已作答',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    
    // 更新选项选中状态
    options.forEach((option, i) => {
      option.isSelected = i === index;
    });
    
    // 判断正确性
    const userAnswer = options[index].label;
    const isCorrect = userAnswer === this.data.correctAnswer;
    const status = isCorrect ? 'correct' : 'wrong';
    
    // 获取题目ID
    const questionId = this.data.questionIdMap[currentIndex] || `q_${currentIndex}`;
    
    // 更新答题状态和答题卡
    const answerStatus = { ...this.data.answerStatus, [currentIndex]: status };
    const questionNumbers = [...this.data.questionNumbers];
    questionNumbers[currentIndex].status = status;
    
    // 更新增强答题状态，包含更多信息
    const enhancedAnswerStatus = { 
      ...this.data.enhancedAnswerStatus, 
      [currentIndex]: {
        status: status,
        questionId: questionId,
        userAnswer: userAnswer,
        correctAnswer: this.data.correctAnswer,
        timestamp: Date.now(),
        isCorrect: isCorrect
      }
    };
    
    this.setData({
      'questionData.options': options,
      userAnswer,
      showResult: true,
      answerStatus,
      questionNumbers,
      enhancedAnswerStatus  // 新增：保存增强答题状态
    });
    
    // 更新答题统计
    this.updateAnswerStats();
    
    // 显示答题结果
    wx.showToast({
      title: isCorrect ? '回答正确！' : '回答错误',
      icon: isCorrect ? 'success' : 'error',
      duration: 1500
    });
    
    // 显示答题进度
    const answeredCount = Object.keys(answerStatus).length;
    const correctCount = Object.values(answerStatus).filter(s => s === 'correct').length;
    const progress = Math.round((answeredCount / this.data.totalQuestions) * 100);
    
    
  },

  /**
   * 显示解析
   */
  showAnalysis() {
    this.setData({ showAnalysis: true });
  },

  /**
   * 切换标签页（解析/评论/笔记）
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  /**
   * 显示纠错弹窗
   */
  showCorrection() {
    wx.showModal({
      title: '有偿纠错',
      content: '发现题目错误？点击确定提交纠错申请',
      confirmText: '确定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({ title: '纠错申请已提交', icon: 'success' });
        }
      }
    });
  },

  /**
   * 编辑题目（待开发）
   */
  editQuestion() {
    wx.showToast({ title: '编辑功能开发中', icon: 'none' });
  },

  /**
   * 分享题目
   */
  shareQuestion() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  /**
   * 跳转到设置页面
   */
  showSettings() {
    wx.navigateTo({
      url: '/index/pages/questionBankDesign/questionBankDesign',
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ title: '跳转失败', icon: 'none' })
      }
    })
  },



  /**
   * 笔记输入
   */
  onNoteInput(e) {
    this.setData({ noteText: e.detail.value });
  },

  /**
   * 保存笔记
   */
  async saveNote() {
    const { noteText, questions, currentIndex } = this.data;
    const qid = questions[currentIndex]?.id || questions[currentIndex]?.question_id;
    if (!qid) return;
    
    // 获取用户ID
    const userId = this.getUserId();
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    
    try {
      await noteService.saveNote({
        questionId: qid,
        content: noteText,
        userId: userId
      });
      
      wx.showToast({ title: '笔记保存成功', icon: 'success' });
    } catch (err) {
      console.error('保存笔记失败:', err);
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  },

  /**
   * 删除笔记
   */
  deleteNote() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条笔记吗？',
      success: async (res) => {
        if (res.confirm) {
          const { questions, currentIndex } = this.data;
          const qid = questions[currentIndex]?.id || questions[currentIndex]?.question_id;
          if (qid) {
            try {
              await noteService.deleteNote(qid);
              this.setData({ noteText: '' });
              wx.showToast({ title: '笔记已删除', icon: 'success' });
            } catch (err) {
              console.error('删除笔记失败:', err);
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          }
        }
      }
    });
  },

/**
 * 切换收藏状态
 */
toggleFavorite() {
  this.setData({ loading: true });
  wx.showLoading({ title: '处理中...' });

  const { isFavorite, favoriteId: originalFavoriteId } = this.data;
  const { questions, currentIndex } = this.data;
  const qid = questions[currentIndex]?.id || questions[currentIndex]?.question_id;
  const userId = this.getUserId();
  
  console.log(`修改收藏状态：用户ID: ${userId}, 题目ID: ${qid}, 当前状态: ${isFavorite}, 历史记录ID: ${originalFavoriteId}`);
  
  if (!qid || !userId) {
    this.setData({ loading: false });
    wx.hideLoading();
    wx.showToast({ title: '请先登录或题目ID无效', icon: 'none' });
    return;
  }

  // 有历史记录ID，执行更新
  if (originalFavoriteId != null) {
    http.put('/wjq/favoritequestion', {
      id: originalFavoriteId,
      userId: userId,
      questionId: qid,
      del: isFavorite ? 0 : 1
    })
    .then(res => {
      if (res.code === 200) {
        // 接口成功，更新状态
        this.setData({ isFavorite: !isFavorite });
        wx.showToast({ 
          title: !isFavorite ? '已收藏' : '已取消收藏', 
          icon: !isFavorite ? 'success' : 'none' 
        });
      } else {
        wx.showToast({ title: res.msg || '操作失败', icon: 'none' });
        console.warn('更新收藏失败，保持原始状态', res);
      }
    })
    .catch(err => {
      console.error('更新收藏状态失败:', err);
      wx.showToast({ title: '网络异常，状态已同步', icon: 'none' });
      this.checkFavoriteStatus(true);
    })
    .finally(() => {
      this.setData({ loading: false });
      wx.hideLoading();
    });
  } 
  // 无历史记录，执行插入
  else {
    http.post('/wjq/favoritequestion', {
      userId: userId,
      questionId: qid,
      del: 1
    })
    .then(res => {
      if (res.code === 200) {
        // 调用返回Promise的checkFavoriteStatus
        this.checkFavoriteStatus(true)
          .then(() => {
            wx.showToast({ title: '已收藏', icon: 'success' });
          })
          .catch(() => {
            wx.showToast({ title: '收藏成功，但状态同步失败', icon: 'none' });
          });
      } else {
        wx.showToast({ title: res.msg || '收藏失败', icon: 'none' });
      }
    })
    .catch(err => {
      console.error('插入收藏记录失败:', err);
      if (err.message.includes('Duplicate entry')) {
        this.checkFavoriteStatus(true)
          .then(() => {
            wx.showToast({ title: '已收藏，状态已同步', icon: 'none' });
          });
      } else {
        wx.showToast({ title: '网络异常，收藏失败', icon: 'none' });
      }
    })
    .finally(() => {
      this.setData({ loading: false });
      wx.hideLoading();
    });
  }
},


/**
 * 检查当前题目收藏状态（修改为返回Promise）
 * @param {boolean} forceUpdate - 是否强制更新UI状态
 * @returns {Promise} - 返回Promise便于链式调用
 */
checkFavoriteStatus(forceUpdate = false) {
  return new Promise((resolve, reject) => {
    const { questions, currentIndex } = this.data;
    const qid = questions[currentIndex]?.id || questions[currentIndex]?.question_id;
    const userId = this.getUserId();
    
    console.log(`检查收藏状态 - 用户ID: ${userId}, 题目ID: ${qid}`);
    
    if (!qid || !userId) {
      reject(new Error('题目ID或用户ID无效'));
      return;
    }

    http.get(`/wjq/favoritequestion/list1?userId=${userId}&questionId=${qid}`)
      .then(res => {
        if (res.code === 200) {
          const list = res.rows || [];
          let isFavorite = false;
          let favoriteId = null;
          
          if (list.length > 0) {
            const record = list[0];
            favoriteId = record.id;
            isFavorite = record.del === 1; // del=1才是已收藏
          }
          
          // 强制更新或状态变化时才更新UI
          if (forceUpdate || this.data.isFavorite !== isFavorite || this.data.favoriteId !== favoriteId) {
            this.setData({ isFavorite, favoriteId }, () => {
              console.log(`收藏状态更新: ${isFavorite ? '已收藏' : '未收藏'}, 记录ID: ${favoriteId}`);
              resolve(true); // 状态更新成功
            });
          } else {
            resolve(false); // 状态未变化
          }
        } else {
          console.warn('查询收藏状态接口返回非成功状态:', res.code);
          reject(new Error(`接口错误: ${res.msg || '未知错误'}`));
        }
      })
      .catch(err => {
        console.error('查询收藏状态失败:', err);
        reject(err);
      });
  });
},

  
  /**
   * 添加错题到错题库
   */
  addToWrongQuestions(e) {
    const questionId = e.currentTarget.dataset.questionId;
    if (!questionId) {
      wx.showToast({ title: '题目ID无效', icon: 'none' });
      return;
    }
    
    // 获取用户ID
    const userId = this.getUserId();
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    
    // 检查是否已经添加过
    if (this.data.isAddedToWrongQuestions) {
      wx.showToast({ title: '已添加到错题库', icon: 'none' });
      return;
    }
    
    // 调用后端接口添加错题
    http.post('/wjq/wrongquestion', {
      questionId: questionId,
      userId: userId
    })
    .then(res => {
      if (res && res.code === 200) {
        this.setData({ isAddedToWrongQuestions: true });
        wx.showToast({ title: '已添加到错题库', icon: 'success' });
      } else {
        wx.showToast({ title: '添加失败', icon: 'none' });
      }
    })
    .catch(err => {
      console.error('添加错题失败:', err);
      wx.showToast({ title: '添加失败', icon: 'none' });
    });
  },

  /**
   * 查看错题
   */
  showWrongQuestions() {
    const wrongIndexes = Object.entries(this.data.answerStatus)
      .filter(([_, status]) => status === 'wrong')
      .map(([index]) => parseInt(index));
      
    if (wrongIndexes.length === 0) {
      wx.showToast({ title: '没有错题', icon: 'none' });
      return;
    }
    
    wx.navigateTo({
      url: `/index/pages/wrongQuestions/wrongQuestions?bankId=${this.data.questionBankId}`,
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({ title: '跳转失败', icon: 'none' });
      }
    });
  },



  /**
   * 显示/隐藏答题卡
   */
  showAnswerCard() { this.setData({ showAnswerCardModal: true }); },
  hideAnswerCard() { this.setData({ showAnswerCardModal: false }); },

  /**
   * 阻止事件冒泡（用于弹窗内部点击）
   */
  stopPropagation() {},

  /**
   * 跳转到指定题目
   */
  jumpToQuestion(e) {
    const number = e.currentTarget.dataset.number;
    const index = number - 1; // 转换为索引
    if (index < 0 || index >= this.data.totalQuestions) return;
    
    this.setData({
      currentIndex: index,
      showAnswerCardModal: false
    });
    
    // 加载指定题目的数据
    this.loadQuestionData(index);
    
    // 如果该题已作答，显示答题结果
    const answerStatus = this.data.answerStatus[index];
    if (answerStatus) {
      this.setData({
        showResult: true,
        userAnswer: this.data.userAnswer
      });
    }
  },

  /**
   * 通过题目ID跳转到指定题目
   */
  jumpToQuestionById(questionId, fallbackIndex) {

    
    if (!questionId) {
      
      // 如果没有题目ID，使用备用索引
      this.jumpToQuestion(fallbackIndex);
      return;
    }
    
    // 在题目列表中查找指定ID的题目，优先使用question_id字段
    const questionIndex = this.data.questions.findIndex(q => 
      q.question_id == questionId ||  // 优先使用question_id
      q.id == questionId || 
      q.questionId == questionId
    );
    
    if (questionIndex !== -1) {
      
      this.jumpToQuestion(questionIndex);
    } else {
      
      // 如果找不到，使用备用索引
      this.jumpToQuestion(fallbackIndex);
    }
  },

  /**
   * 提交所有答案
   */
  submitAnswers() {
    const { answerStatus, totalQuestions } = this.data;
    const answeredCount = Object.keys(answerStatus).length;
    const correctCount = Object.values(answerStatus).filter(s => s === 'correct').length;
    const wrongCount = Object.values(answerStatus).filter(s => s === 'wrong').length;
    const unansweredCount = totalQuestions - answeredCount;
    const correctRate = totalQuestions ? Math.round((correctCount / totalQuestions) * 100) : 0;
    
    // 构建详细的答题报告
    const report = {
      total: totalQuestions,
      correct: correctCount,
      wrong: wrongCount,
      unanswered: unansweredCount,
      correctRate: correctRate,
      answeredCount: answeredCount
    };
    
    wx.showModal({
      title: '答题完成',
      content: `共${totalQuestions}题\n答对：${correctCount}题\n答错：${wrongCount}题\n未答：${unansweredCount}题\n正确率：${correctRate}%`,
      confirmText: '返回首页',
      cancelText: '查看解析',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/index/index'
          });
        } else {
             this.setData({ showAnswerCardModal: false });
          // 可以在这里跳转到答题报告页面
          this.showAnswerReport(report);
        }
      }
    });
  },

  /**
   * 显示答题报告
   */
  showAnswerReport(report) {
    // 停止计时器并获取最终时间
    const finalTime = this.stopTimer();
    console.log('答题完成，最终耗时:', finalTime, '秒');
    
    // 构建答题报告数据
    const reportData = {
      total: report.total,
      correct: report.correct,
      wrong: report.wrong,
      unanswered: report.unanswered,
      correctRate: report.correctRate,
      totalTime: finalTime, // 使用真实的计时时间
      completeTime: this.formatTime(new Date()),
      questionBankName: this.data.questionBankId ? `题库${this.data.questionBankId}` : '章节练习',
      questionBankId: this.data.questionBankId, // 添加题库ID
      questions: this.data.questions,
      answerStatus: this.data.answerStatus,
      // 新增：增强答题状态，包含题目ID和详细答题信息
      enhancedAnswerStatus: this.data.enhancedAnswerStatus,
      questionIdMap: this.data.questionIdMap
    };
    
    console.log('构建答题报告数据:', {
      questionBankId: this.data.questionBankId,
      questionBankName: reportData.questionBankName,
      reportData: reportData
    });
    
    // 保存答题报告到本地存储
    try {
      const storageKey = `answerReport_${this.data.questionBankId || 'default'}`;
      wx.setStorageSync(storageKey, reportData);
      
    } catch (e) {
      console.error('保存答题报告失败:', e);
    }
    
    // 跳转到答题详情页面
    wx.navigateTo({
      url: `/index/pages/answerReport/answerReport?reportData=${encodeURIComponent(JSON.stringify(reportData))}`,
      success: () => {

      },
      fail: (err) => {
        console.error('跳转到答题详情页面失败:', err);
        // 如果跳转失败，显示弹窗作为备选方案
        wx.showModal({
          title: '答题报告',
          content: `本次练习完成！\n\n总题数：${report.total}\n答对：${report.correct}题\n答错：${report.wrong}题\n未答：${report.unanswered}题\n正确率：${report.correctRate}%`,
          confirmText: '知道了',
          showCancel: false
        });
      }
    });
  },

  /**
   * 开始计时
   */
  startTimer() {
    if (this.data.isTimerRunning) {
      console.log('计时器已在运行中');
      return;
    }
    
    const startTime = Date.now();
    console.log('开始计时，开始时间:', startTime);
    
    this.setData({
      startTime: startTime,
      elapsedSeconds: 0,
      isTimerRunning: true
    });
    
    // 启动计时器，每秒更新一次
    const timerInterval = setInterval(() => {
      const currentTime = Date.now();
      const elapsedSeconds = Math.floor((currentTime - startTime) / 1000);
      
      this.setData({
        elapsedSeconds: elapsedSeconds
      });
    }, 1000);
    
    this.setData({ timerInterval: timerInterval });
    console.log('计时器已启动');
  },

  /**
   * 停止计时
   */
  stopTimer() {
    if (!this.data.isTimerRunning) {
      console.log('计时器未运行');
      return 0;
    }
    
    if (this.data.timerInterval) {
      clearInterval(this.data.timerInterval);
    }
    
    const finalElapsedSeconds = this.data.elapsedSeconds;
    console.log('停止计时，总耗时:', finalElapsedSeconds, '秒');
    
    this.setData({
      isTimerRunning: false,
      timerInterval: null
    });
    
    return finalElapsedSeconds;
  },

  /**
   * 计算总用时（返回秒数）
   */
  calculateTotalTime() {
    // 如果计时器正在运行，返回当前已过时间
    if (this.data.isTimerRunning) {
      return this.data.elapsedSeconds;
    }
    
    // 如果计时器已停止，返回最终时间
    if (this.data.elapsedSeconds > 0) {
      return this.data.elapsedSeconds;
    }
    
    // 默认返回0
    return 0;
  },

  /**
   * 格式化时间
   */
  formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  /**
   * 上一题
   */
  prevQuestion() {
    if (this.data.currentIndex <= 0) {
      wx.showToast({ title: '已是第一题', icon: 'none' });
      return;
    }
    const prevIndex = this.data.currentIndex - 1;
    this.setData({ currentIndex: prevIndex });
    this.loadQuestionData(prevIndex);
  },

  /**
   * 下一题或交卷
   */
 /**
 * 下一题或交卷
 */
nextOrSubmit() {
  const { currentIndex, totalQuestions } = this.data;
  if (currentIndex < totalQuestions - 1) {
    // 不是最后一题，跳转到下一题
    const nextIndex = currentIndex + 1;
    this.setData({ currentIndex: nextIndex });
    this.loadQuestionData(nextIndex);
  } else {
    // 是最后一题，显示提交确认
    this.setData({ showSubmitConfirm: true });
  }
},

  /**
   * 确认交卷
   */
  confirmSubmit() {
    this.setData({ showSubmitConfirm: false });
    this.submitAnswers();
  },

  /**
   * 取消交卷
   */
  cancelSubmit() {
    this.setData({ showSubmitConfirm: false });
  },

  /**
   * 更新答题统计
   */
  updateAnswerStats() {
    const { enhancedAnswerStatus, totalQuestions } = this.data;
    
    // 使用增强答题状态进行统计
    const answeredCount = Object.keys(enhancedAnswerStatus).length;
    const correctCount = Object.values(enhancedAnswerStatus).filter(item => item.status === 'correct').length;
    const wrongCount = Object.values(enhancedAnswerStatus).filter(item => item.status === 'wrong').length;
    const unansweredCount = totalQuestions - answeredCount;
    const correctRate = totalQuestions ? Math.round((correctCount / totalQuestions) * 100) : 0;
    const progressPercentage = totalQuestions ? Math.round((answeredCount / totalQuestions) * 100) : 0;
    
    // 计算平均答题时间（如果有时间戳）
    let averageTime = 0;
    if (answeredCount > 0) {
      const timestamps = Object.values(enhancedAnswerStatus).map(item => item.timestamp).filter(Boolean);
      if (timestamps.length > 1) {
        const timeDiffs = [];
        for (let i = 1; i < timestamps.length; i++) {
          timeDiffs.push(timestamps[i] - timestamps[i-1]);
        }
        averageTime = Math.round(timeDiffs.reduce((sum, diff) => sum + diff, 0) / timeDiffs.length / 1000);
      }
    }
    
    this.setData({
      answeredCount,
      correctCount,
      wrongCount,
      unansweredCount,
      correctRate,
      progressPercentage,
      averageAnswerTime: averageTime
    });
    

  },

  /**
   * 加载指定题目的数据（按需加载选项和评论）
   */
  loadQuestionData(index) {
    // 新增：检查收藏状态
  this.checkFavoriteStatus();

    // 重置当前题显示状态（保持选项显示）
    this.setData({
      showOptions: true,  // 保持选项显示
      showResult: false,
      showAnalysis: false,
      userAnswer: '',
      activeTab: 'analysis',
      comments: [],
      isAddedToWrongQuestions: false  // 重置错题添加状态
    });
    
    const { questions } = this.data;
    if (!Array.isArray(questions) || !questions[index]) {

      return;
    }

    // 转换题目基础数据
    const mapped = this.transformBackendQuestion(questions[index]);
    const qid = questions[index].id || questions[index].question_id;
    
    // 检查是否是模拟题目（有预定义选项）
    if (questions[index].options && Array.isArray(questions[index].options)) {

      // 使用预定义的选项数据
      mapped.options = questions[index].options;
      mapped.correctAnswer = questions[index].correctAnswer || 'A';
      
      // 直接显示题目数据
      this.setData({
        questionData: mapped,
        correctAnswer: mapped.correctAnswer
      });
      

    } else if (qid) {
      // 真实题目，按需加载选项
      if (this.data.questionOptionsMap[qid]) {
        // 已加载，直接使用缓存
        const backendOptions = this.data.questionOptionsMap[qid];
        const built = this.buildOptionsFromBackendOptions(backendOptions, mapped.correctAnswer);
        mapped.options = built.options;
        mapped.correctAnswer = built.correctLabel || mapped.correctAnswer;
        
        // 更新当前题数据
        this.setData({
          questionData: mapped,
          correctAnswer: mapped.correctAnswer
        });
      } else {
        // 未加载，发起请求
        this.fetchOptionsByQuestionId(qid, index);
        
        // 先显示基础题目信息，选项加载中
        this.setData({
          questionData: mapped,
          correctAnswer: mapped.correctAnswer
        });
      }
      

    } else {
      // 没有题目ID，直接显示基础信息
      this.setData({
        questionData: mapped,
        correctAnswer: mapped.correctAnswer
      });
    }
    
    // 回显已答题目的状态
    const answerStatus = this.data.answerStatus;
    if (answerStatus[index]) {
      const status = answerStatus[index];
      const userAnswer = this.data.userAnswer;
      
      // 根据答题状态设置选项显示
      if (status === 'correct' || status === 'wrong') {
        mapped.options.forEach(option => {
          // 找到用户选择的选项
          if (option.label === userAnswer) {
            option.isSelected = true;
          }
        });
        
        this.setData({ 
          showOptions: true, 
          showResult: true,
          userAnswer: userAnswer
        });
      }
    }
    
    // 如果是最后一题，检查是否所有题目都已作答
    if (index === this.data.totalQuestions - 1) {
      const answeredCount = Object.keys(this.data.answerStatus).length;
      if (answeredCount === this.data.totalQuestions) {
        // 所有题目都已作答，提示可以交卷
        setTimeout(() => {
          wx.showModal({
            title: '答题完成',
            content: '所有题目已完成，可以交卷查看成绩！',
            confirmText: '立即交卷',
            cancelText: '继续检查',
            success: (res) => {
              if (res.confirm) {
                this.submitAnswers();
              }
            }
          });
        }, 1000);
      }
    }
  },

  /**
   * 构建标准选项数组（处理后端返回的选项数据）
   */
  buildOptionsFromBackendOptions(backendOptions, fallbackCorrect) {
    
    const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
    let detectedCorrectIndex = -1;
    let stdOptions = [];
    
    // 检查后端返回的数据结构
    if (Array.isArray(backendOptions)) {

      // 如果是数组格式，按原来的逻辑处理
      stdOptions = backendOptions.slice(0, labels.length).map((opt, i) => {
        const text = opt.text || opt.content || opt.optionText || opt.title || '';
        const rawCorrect = opt.isCorrect || opt.correct || opt.isRight || false;
        const isCorrect = rawCorrect === true || rawCorrect === 1 || rawCorrect === '1' || String(rawCorrect).toLowerCase() === 'true';
        if (isCorrect && detectedCorrectIndex === -1) detectedCorrectIndex = i;
        return { label: labels[i], text, isCorrect, isSelected: false };
      });
    } else if (typeof backendOptions === 'object' && backendOptions !== null) {
      
      // 如果是对象格式，处理 optionA, optionB, optionC, optionD 等字段
      const optionFields = ['optionA', 'optionB', 'optionC', 'optionD', 'optionE', 'optionF'];
      const correctOptions = backendOptions.correctOptions || backendOptions.correctAnswer || '';
      
      
      
      stdOptions = optionFields.map((field, i) => {
        const text = backendOptions[field] || '';
        if (!text) return null; // 跳过空的选项
        
        // 判断是否为正确答案
        const isCorrect = correctOptions.includes(labels[i]) || correctOptions === labels[i];
        if (isCorrect && detectedCorrectIndex === -1) detectedCorrectIndex = i;
        
        
        
        return { 
          label: labels[i], 
          text, 
          isCorrect, 
          isSelected: false 
        };
      }).filter(Boolean); // 过滤掉空的选项
      
      // 如果从对象中找到了正确答案，更新 detectedCorrectIndex
      if (detectedCorrectIndex === -1 && correctOptions) {
        const correctIndex = labels.findIndex(label => correctOptions.includes(label));
        if (correctIndex !== -1) {
          detectedCorrectIndex = correctIndex;
        }
      }
    }
    
    // 推导正确答案标签
    let correctLabel = '';
    if (detectedCorrectIndex >= 0) correctLabel = labels[detectedCorrectIndex];
    if (!correctLabel && fallbackCorrect) correctLabel = String(fallbackCorrect).toUpperCase();
    if (!correctLabel && stdOptions.length) correctLabel = stdOptions[0].label;
    
    // 如果没有找到正确答案，尝试从 correctOptions 字段获取
    if (!correctLabel && backendOptions.correctOptions) {
      correctLabel = String(backendOptions.correctOptions).toUpperCase();
    }
    

    
    return { options: stdOptions, correctLabel };
  },

  /**
   * 切换是否显示详细内容
   */
  toggleDetailContent() {
    const { showDetailContent } = this.data;
    this.setData({
      showDetailContent: !showDetailContent
    });
    
    wx.showToast({
      title: !showDetailContent ? '已显示详细内容' : '已隐藏详细内容',
      icon: 'none',
      duration: 1500
    });
  },

  /**
   * 强制显示详细内容（用于错题复习等场景）
   */
  forceShowDetailContent() {
    this.setData({
      showDetailContent: true,
      detailContentMode: 'review'
    });
  },

  /**
   * 强制隐藏详细内容（用于正常答题场景）
   */
  forceHideDetailContent() {
    this.setData({
      showDetailContent: false,
      detailContentMode: 'normal'
    });
  },

  /**
   * 页面加载时初始化
   */
  onLoad(options) {

    // 根据路由参数判断显示模式
    let showDetailContent = false;
    let detailContentMode = 'normal';
    
    // 先设置默认值，稍后根据params内容更新
    showDetailContent = false;
    detailContentMode = 'normal';
    
    console.log('chapterPractice页面接收到的参数:', options);

    // 处理从Order页面传递过来的参数（questionBankId和subjectId）
    if (options?.questionBankId && options?.subjectId) {
      console.log('从Order页面接收参数 - questionBankId:', options.questionBankId, 'subjectId:', options.subjectId);
      
      this.setData({ 
        questionBankId: options.questionBankId,
        subjectId: options.subjectId
      });
      
      // 使用题库ID加载题目
      this.fetchQuestionsByBankId(options.questionBankId);
      
      // 启动计时器（正常答题模式）
      setTimeout(() => {
        this.startTimer();
      }, 100);
      
      return; // 直接返回，不执行后续逻辑
    }

    // 处理从答题报告传递过来的参数
    if (options?.params) {
      try {
        const params = JSON.parse(decodeURIComponent(options.params));

        

        

        
        // 设置题库ID
        if (params.questionBankId) {
          this.setData({ questionBankId: params.questionBankId });
          this.fetchQuestionsByBankId(params.questionBankId);
        } else {
          // 如果没有题库ID，但有答题状态数据，尝试从第一题的ID推断题库
          if (params.answerStatus && params.answerStatus.length > 0) {
            const firstQuestion = params.answerStatus[0];
            if (firstQuestion.questionId) {

              // 这里可以根据题目ID的规律来推断题库，或者直接加载题目
              // 暂时先设置一个默认值
              this.setData({ questionBankId: 'default' });
              // 或者可以调用一个通用的题目加载方法
              this.loadQuestionsFromAnswerStatus(params.answerStatus);
            }
          }
        }
        
        // 如果是错题模式，设置错题数据
        if (params.mode === 'wrong' && params.wrongQuestions) {
          this.setData({
            wrongQuestions: params.wrongQuestions,
            totalQuestions: params.totalQuestions || params.wrongQuestions.length
          });
        }
        
        // 如果是全部解析模式，设置答题状态
        if (params.mode === 'review' && params.answerStatus) {
          // 设置为复习模式，显示详细内容
          showDetailContent = true;
          detailContentMode = 'review';

          
          this.setData({
            answerStatus: params.answerStatus,
            totalQuestions: params.totalQuestions
          });
          

          
          // 如果有指定目标题目，跳转到该题
          if (params.targetQuestionNumber && params.targetQuestionIndex !== undefined) {

            
            // 如果有题目ID，优先使用ID进行定位
            if (params.targetQuestionId) {

              this.waitForQuestionsLoaded(() => {
                this.jumpToQuestionById(params.targetQuestionId, params.targetQuestionIndex);
              });
            } else {
              // 否则使用索引定位

              this.waitForQuestionsLoaded(() => {
                this.jumpToQuestion(params.targetQuestionIndex);
              });
            }
          }
        }
        
        // 如果是错题模式，设置错题数据
        if (params.mode === 'wrong' && params.wrongQuestions) {
          // 设置为错题模式，显示详细内容
          showDetailContent = true;
          detailContentMode = 'review';

          
          this.setData({
            wrongQuestions: params.wrongQuestions,
            totalQuestions: params.totalQuestions || params.wrongQuestions.length
          });
        }
        
        // 根据来源设置显示模式
        if (params.from === 'answerReport') {
          showDetailContent = true;
          detailContentMode = 'review';

        }
        
              } catch (e) {
          console.error('解析答题报告参数失败:', e);
        }
      }
      // 接收题库ID并加载题目（兼容原有方式）
      else if (options?.id) {
        const qbId = isNaN(Number(options.id)) ? options.id : Number(options.id);
        this.setData({ questionBankId: qbId });
        this.fetchQuestionsByBankId(qbId);
      }
      
      // 统一设置显示模式
      this.setData({
        showDetailContent,
        detailContentMode
      });
      


    // 支持直接跳转指定题目
    if (options?.questionId && this.data.questions.length) {
      const questionIndex = this.data.questions.findIndex(
        q => q.id == options.questionId || q.question_id == options.questionId
      );
      if (questionIndex !== -1) {
        this.setData({ currentIndex: questionIndex });
        this.loadQuestionData(questionIndex);
      }
    }
    
    // 启动计时器（如果是正常答题模式，不是复习模式）
    if (detailContentMode === 'normal') {
      console.log('启动答题计时器');
      setTimeout(() => {
        this.startTimer();
      }, 100);
    } else {
      console.log('复习模式，不启动计时器');
    }
  },

  /**
   * 等待题目加载完成
   */
  waitForQuestionsLoaded(callback) {
    if (this.data.questions && this.data.questions.length > 0) {

      callback();
    } else {
      
      // 如果题目还没加载，等待一下再试
      setTimeout(() => {
        this.waitForQuestionsLoaded(callback);
      }, 100);
    }
  },

  /**
   * 跳转到指定题目
   */
  jumpToQuestion(questionIndex) {

    
    if (questionIndex >= 0 && questionIndex < this.data.totalQuestions) {
      
      this.setData({ currentIndex: questionIndex });
      this.loadQuestionData(questionIndex);
      
      // 显示提示
      wx.showToast({
        title: `已跳转到第${questionIndex + 1}题`,
        icon: 'none',
        duration: 1500
      });
    } else {

    }
  },

  /**
   * 页面卸载时清理计时器
   */
  onUnload() {
    if (this.data.timerInterval) {
      clearInterval(this.data.timerInterval);
      console.log('页面卸载，清理计时器');
    }
  },

  /**
   * 页面隐藏时暂停计时器
   */
  onHide() {
    if (this.data.isTimerRunning) {
      console.log('页面隐藏，暂停计时器');
      // 可以选择暂停计时器或继续计时
    }
  },

  /**
   * 页面显示时恢复计时器
   */
  onShow() {
    if (this.data.isTimerRunning && !this.data.timerInterval) {
      console.log('页面显示，恢复计时器');
      this.startTimer();
    }
  },

  /**
   * 分享配置
   */
  onShareAppMessage() {
    const { questionData, questionBankId, currentIndex } = this.data;
    return {
      title: '章节练习 - ' + questionData.title,
      path: `/index/pages/chapterPractice/chapterPractice?id=${questionBankId}&questionId=${currentIndex + 1}`
    };
  },

  /**
   * 获取用户ID
   */
  getUserId() {
    const { getCurrentUser } = require('../../../utils/userManager.js');
    const user = getCurrentUser();
    return user?.userInfo?.userId || null;
  },

  /**
   * 从答题状态数据中加载题目（当没有题库ID时使用）
   */
  loadQuestionsFromAnswerStatus(answerStatus) {

    if (!Array.isArray(answerStatus) || answerStatus.length === 0) {
      return;
    }

    // 构建题目列表（模拟题目数据结构）
    const questions = answerStatus.map((item, index) => ({
      id: item.questionId,
      question_id: item.questionId,
      title: `第${item.questionNumber}题`,
      content: `这是第${item.questionNumber}题的模拟内容。题目ID: ${item.questionId}，答题状态: ${item.status === 'correct' ? '答对' : '答错'}。`,
      type: '单选题',
      index: index,
      // 添加模拟选项数据
      options: [
        { label: 'A', text: '选项A - 这是第一个选项', isCorrect: false, isSelected: false },
        { label: 'B', text: '选项B - 这是第二个选项', isCorrect: false, isSelected: false },
        { label: 'C', text: '选项C - 这是第三个选项', isCorrect: false, isSelected: false },
        { label: 'D', text: '选项D - 这是第四个选项', isCorrect: false, isSelected: false }
      ],
      correctAnswer: 'A' // 模拟正确答案
    }));

    // 初始化题目状态数组
    const questionNumbers = answerStatus.map((item, index) => ({ 
      number: index + 1, 
      status: item.status 
    }));

    // 初始化题目ID映射
    const questionIdMap = {};
    answerStatus.forEach((item, index) => {
      questionIdMap[index] = item.questionId;
    });

    // 设置页面数据
    this.setData({
      questions: questions,
      totalQuestions: questions.length,
      currentIndex: 0,
      questionNumbers: questionNumbers,
      questionIdMap: questionIdMap,
      answerStatus: {}, // 重置答题状态，因为这是复习模式
      enhancedAnswerStatus: {} // 重置增强答题状态
    });



    // 加载第一题数据
    if (questions.length > 0) {
      this.loadQuestionData(0);
    }
  }
});